/*
 * @Author: webcc
 * @Date: 2022-10-22 22:17:08
 * @LastEditTime: 2022-10-24 10:09:31
 * @email: webcc.coder@qq.com
 */
import React, { Component, createRef } from 'react'
import { Card, Breadcrumb, Form, Button, Input, Radio, DatePicker, Space, Upload, Tag, message, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import Channel from 'components/Channel'
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import style from './index.module.scss'
import { baseURL } from 'utils/request';
import { reqPublishArticle, reqGetArticleInfo, reqUpdateArticle } from 'api/article'
import { Link } from 'react-router-dom'
export default class ArticlePublish extends Component {
    state = {
        type: 1,
        fileList: [],
        previewOpen: false,
        previewImage: '',
        id: this.props.match.params.id,
    }
    formRef = createRef()
    render() {
        return (
            <div className={style.publish}>
                <Card title={
                    <Breadcrumb>
                        <Breadcrumb.Item>
                            <Link to="/home">首页</Link>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>{this.state.id ? '编辑文章' : '发布文章'}</Breadcrumb.Item>
                    </Breadcrumb>
                }>
                    <Form
                        ref={this.formRef}
                        labelCol={{ span: 4 }}
                        size="large"
                        onFinish={this.onFinish}
                        validateTrigger={['onBlur', 'onChange']}
                        // 由于react-quill value不为空，必须为content提供默认值
                        initialValues={{ content: '', type: this.state.type }}
                    >
                        <Form.Item label="标题" name="title" rules={[
                            {
                                required: true,
                                message: "标题不能为空"
                            }
                        ]}>
                            <Input style={{ width: 400 }} placeholder="请输入文章标题"></Input>
                        </Form.Item>
                        <Form.Item label="频道" name="channel_id" rules={[
                            {
                                required: true,
                                message: "频道不能为空"
                            }
                        ]}>
                            <Channel></Channel>
                        </Form.Item>
                        <Form.Item label="封面" name="type">
                            <Radio.Group onChange={this.onChange}>
                                <Radio value={1}>单图</Radio>
                                <Radio value={3}>三图</Radio>
                                <Radio value={0}>无图</Radio>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item wrapperCol={{ offset: 4 }}>
                            {
                                this.state.type != 0 && (
                                    <Upload
                                        listType="picture-card"
                                        fileList={this.state.fileList}
                                        action={`${baseURL}upload`}
                                        // 图片名字
                                        name="image"
                                        onChange={this.uploadImage}
                                        onPreview={this.handlePreview}
                                        beforeUpload={this.beforeUpload}
                                    >
                                        {
                                            this.state.fileList.length < this.state.type && (
                                                <PlusOutlined />
                                            )
                                        }
                                    </Upload>

                                )
                            }
                        </Form.Item>
                        <Form.Item label="内容" name="content">
                            <ReactQuill theme="snow" placeholder="请输入文章内容" />
                        </Form.Item>
                        <Form.Item wrapperCol={{ offset: 4 }}>
                            <Space>
                                <Button type="primary" htmlType="submit" size="large">
                                    {this.state.id ? '编辑文章' : '发布文章'}
                                </Button>
                                <Button type="primary" size="large" onClick={this.addDraft}>
                                    存入草稿
                                </Button>
                            </Space>
                        </Form.Item>
                    </Form>
                </Card>
                {/* 图片预览弹框 */}
                <Modal open={this.state.previewOpen} title="图片预览" footer={null} onCancel={this.handleCancel}>
                    <img style={{ width: '100%' }} src={this.state.previewImage} />
                </Modal>
            </div>
        )
    }
    async componentDidMount() {
        if (this.state.id) {
            const res = await reqGetArticleInfo(this.state.id)
            console.log(res)
            this.formRef.current.setFieldsValue({
                ...res.data,
                type: res.data.cover.type,
            })
            let fileList = res.data.cover.images.map(item => {
                return {
                    url: item
                }
            })
            this.setState({
                fileList,
                type: res.data.cover.type
            })
        }

    }
    save = async (values, draft) => {
        let { type } = this.state
        if (this.state.fileList.length != type) {
            return message.warn("上传的图片数量不正确")
        }
        let images = this.state.fileList.map(item => {
            return item.url || item.response.data.url
        })
        if (this.state.id) {
            const res = await reqUpdateArticle({
                ...values,
                cover: {
                    type,
                    images
                },
                id: this.state.id
            }, draft)
            message.success("修改文章成功")
        } else {
            const res = await reqPublishArticle({
                ...values,
                cover: {
                    type,
                    images
                }
            }, draft)
            message.success("上传文章成功")
        }
        this.props.history.push('/home/list')
    }
    // 发布文章
    onFinish = async (values) => {
        this.save(values, false)
    }
    // 存入草稿
    addDraft = async () => {
        let values = await this.formRef.current.validateFields()
        this.save(values, true)
    }
    onChange = (e) => {
        this.setState({
            type: e.target.value,
            fileList: []
        })
    }
    handleCancel = () => {
        this.setState({
            previewOpen: false,
            previewImage: ''
        })
    }
    handlePreview = (file) => {
        this.setState({
            previewOpen: true,
            previewImage: file.url || file.response.data.url
        })
    };
    beforeUpload = (file) => {
        if (file.size > 500 * 1024) {
            message.warn("上传图片不能大于500kb")
            return Upload.LIST_IGNORE;
        }
        if (!['image/png', 'image/jpeg'].includes(file.type)) {
            message.warn("只能上传png或jpg格式的图片")
            return Upload.LIST_IGNORE;
        }
        return true;
    }
    uploadImage = ({ fileList }) => {
        this.setState({
            fileList
        })
    }
}
